
const { spawn }      = require('child_process');
const log4js    = require('../data/log');
const logger    = log4js.getLogger('media');
let child=null;

let Zlmediakit = {
    /**
     * 启动zlmediakit服务
     */
    start:async function(){
        var p = new Promise((resolve, reject)=>{
            child = spawn('pipe/zlkservice.sh',['start']);
            child.on('close',(code)=>{
                logger.info(`子进程退出码:${code}`);
            });
            const {stdin, stdout, stderr} = child;
            stdout.on('data',(data)=>{
                logger.info(`stdout: ${data}`);
                if(data.indexOf('已启动http hook 接口')>-1){
                    resolve('started');
                }
            });
            stderr.on('data', (data)=>{
                logger.error(`stderr: ${data}`);
                reject();
            })
        });
        return p;
    },
    stop:function(){
        var p = new Promise((resolve, reject)=>{
            if(child){
                child.kill(signal='SIGTERM');
                resolve();
            }else{
                child = spawn('pipe/zlkservice.sh',['stop']);
                child.on('close',(code)=>{
                    logger.info(`子进程退出码:${code}`);
                });
                const {stdin, stdout, stderr} = child;
                stdout.on('data',(data)=>{
                    logger.info(`stdout: ${data}`);
                    if(data.indexOf('程序退出完毕')>-1 || data.indexOf('不需要杀进程')>-1){
                        resolve('stopped');
                    }
                });
                stderr.on('data', (data)=>{
                    logger.error(`stderr: ${data}`);
                    reject();
                });
            }
        });
        return p;
    }
};

module.exports=Zlmediakit;
